package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.db.GoodsDetailMsBean
import com.example.library_common.db.UserDatabase
import com.example.library_common.global.AppGlobals
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.shushiyunsst.R
import com.example.shushiyunsst.util.CONFIRM_TAKE_ORDER
import com.example.shushiyunsst.util.SHOP_CAR
import com.example.shushiyunsst.util.startNavigation
import com.example.wallet.db.UserInfoManager
import ikidou.reflect.TypeBuilder
import java.lang.reflect.Type

@Route(path = SHOP_CAR)
class ShopCarFragment : SimpleListFragment<GoodsDetailMsBean>(), View.OnClickListener,
    OnItemChildClickListener {

    private val user = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

    private lateinit var goodsCountTv: TextView

    private lateinit var manager: TextView

    private lateinit var payingNowLy: View

    private lateinit var allCostTv: TextView

    private lateinit var takeOrder: TextView

    private lateinit var deleteTv: TextView

    private lateinit var selectedCount: TextView

    private lateinit var allSelected: CheckBox

    private val icon =AppGlobals.getApplication().getString(R.string.wallet_sst)

    private val selectLs = mutableListOf<GoodsDetailMsBean>()

    private val shopCarBean = UserDatabase.getInstance()
        .shopCarBean()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
        isEnableLoadMore = false
        isAddDividerItemDecoration = false
        isAlwaysRefresh = false
    }

    @SuppressLint("SetTextI18n")
    override fun initView(view: View) {
        super.initView(view)
        view.setBackgroundResource(R.color.bg_color)
        mHeader.removeAllViews()
        mHeader.setBackgroundResource(R.color.bg_color_0)
        addHeader(R.layout.comment_header_layout)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.setTitle(R.string.shop_car)
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        addHeader(R.layout.shop_car_header_fragment)

        manager = mHeader.findViewById(R.id.manager)

        goodsCountTv = mHeader.findViewById(R.id.goodsCountTv)

        mFooter.removeAllViews()
        mFooter.setBackgroundResource(R.color.bg_color_0)
        addFooter(R.layout.shop_car_footer_fragment)

        selectedCount = mFooter.findViewById(R.id.selected_count)

        payingNowLy = mFooter.findViewById(R.id.payingNowLy)

        allCostTv = mFooter.findViewById(R.id.allCostTv)

        takeOrder = mFooter.findViewById(R.id.takeOrder)

        deleteTv = mFooter.findViewById(R.id.deleteTv)

        allSelected = mFooter.findViewById(R.id.allSelected)

        allSelected.setOnClickListener(this)

        deleteTv.setOnClickListener(this)

        manager.setOnClickListener(this)

        takeOrder.setOnClickListener(this)

        mAdapter.addChildClickViewIds(
            R.id.check_et,
            R.id.add,
            R.id.cut,
        )

        mAdapter.setOnItemChildClickListener(this)

        fillData()
    }

    @SuppressLint("SetTextI18n")
    private fun fillData() {

        goodsCountTv.text = "${mAdapter.data.size}"

        var cost = 0
        for (e in selectLs) {
            cost += e.goodsPrice
        }
        allCostTv.text = _mActivity.getString(R.string.cnyStr, cost)

        selectedCount.text =
            _mActivity.getString(R.string.selected_count, selectLs.size)

    }

    override fun getItemLayout() = R.layout.shop_car_fragment

    override fun convertItem(helper: JssBaseViewHolder?, item: GoodsDetailMsBean?) {
        helper?.setImageNetUrl(R.id.icon, item?.defaultImg)
            ?.setText(R.id.goodsName, item?.goodsName)
            ?.setText(R.id.priceEtv, "$icon ${item?.goodsPrice}")
            ?.setText(R.id.countTv, "${item?.selectedCount}")
            ?.setCheckBoxChecked(R.id.check_et, selectLs.contains(item))

    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(GoodsDetailMsBean::class.java).endSubType().build()
    }

    @SuppressLint("SetTextI18n")
    override fun netRequest() {

        val cache = shopCarBean
            .getCache(user?.uid)

        loadListDate(cache?.shopCarList22)

        goodsCountTv.text = "${mAdapter.data.size}"

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.takeOrder -> {
                if (selectLs.isEmpty()) {
                    Toast.makeText(_mActivity, "请选择商品", Toast.LENGTH_SHORT).show()
                    return
                }



                ARouter.getInstance()
                    .build(CONFIRM_TAKE_ORDER)
                    .startNavigation(this)
            }
            R.id.manager -> {
                manager.isSelected = !manager.isSelected
                if (!manager.isSelected) {
                    manager.setText(R.string.shop_manager)
                    payingNowLy.visibility = View.VISIBLE
                    deleteTv.visibility = View.GONE
                } else {
                    payingNowLy.visibility = View.GONE
                    deleteTv.visibility = View.VISIBLE
                    manager.setText(R.string.shop_done)
                }
            }
            R.id.allSelected -> {
                if (allSelected.isChecked) {
                    selectLs.addAll(mAdapter.data)
                } else {
                    selectLs.clear()
                }
                mAdapter.notifyDataSetChanged()
                fillData()
            }

            R.id.deleteTv -> {

                if (selectLs.isEmpty()){
                    return
                }

                for (e in selectLs) {
                    mAdapter.remove(e)
                }

                if (mAdapter.data.isEmpty()) {
                    mAdapter.isUseEmpty = true
                    mAdapter.notifyDataSetChanged()
                }
                selectLs.clear()

                onSaveData()

                fillData()

                allSelected.isChecked = false
            }
        }
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, viewItem: View, position: Int) {
        when (viewItem.id) {
            R.id.check_et -> {
                val item = mAdapter.getItem(position)
                if (selectLs.contains(item)) {
                    selectLs.remove(item)
                } else {
                    selectLs.add(item)
                }
                fillData()

                allSelected.isChecked = selectLs.size == mAdapter.data.size
            }
            R.id.add -> {
                val item = mAdapter.getItem(position)
                item.selectedCount += 1
                mAdapter.notifyItemChanged(position)

                onSaveData()
            }
            R.id.cut -> {
                val item = mAdapter.getItem(position)
                if (item.selectedCount>1){
                    item.selectedCount -= 1
                }

                mAdapter.notifyItemChanged(position)

                onSaveData()

            }
        }
    }

    private fun onSaveData(){
        val cache = shopCarBean
            .getCache(user?.uid)
        cache?.shopCarList= JSON.toJSONString(mAdapter.data)
        shopCarBean.save(cache)
    }

    override fun handMessage(msg: MessageWrap?) {
//        super.handMessage(msg)
        if (msg?.message == TO_REFRESH_LIST) {
            selectLs.clear()
            fillData()
            if (!mSwipeRefreshLayout.isRefreshing) {
                mSwipeRefreshLayout.isRefreshing = true
            }
            onRefresh()
        }
    }


}